﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ICMS.PluginInterfaces;
using System.IO;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using commonImportPlugin.Factorys;
using commonImportPlugin.Config;
using System.Runtime.InteropServices;
using commonImportPlugin.Common;
using commonImportPlugin.Configs.PbocFile;

namespace commonImportPlugin.FilesCore.PbocFile
{
    /// <summary>
    /// 《普通模式通用金融数据解析核心类》
    /// 该模式支持金融数据内容是以机器
    /// 码格式，如上海银联格式和绝大部分
    /// 银行。该模式目前已支持80%以上银行
    /// 数据
    /// </summary>
    public class PbocFileCoreClass : PbocFileCore
    {
        PbocBase pbocBase = new PbocBase();
        static PbocFileConfig config = null;
        CommonUtil commonUtil = CommonUtil.GetInstance();
        static Context context;
        //记录总条数
        int pbocDataCounts = 0;
        public PbocFileCoreClass GetInstance()
        {
            if (IsGetConfigSucceed())
            {
                context = Context.GetConfig();
                return new PbocFileCoreClass();
            }
            return null;
        }
        private bool IsGetConfigSucceed()
        {
            config = PbocFileConfig.GetConfig();
            if (config == null)
                return false;
            else
                return true;
        }
        /// <summary>
        /// 获取所有金融数据
        /// </summary>
        /// <param name="pbocFilePaths">金融数据文件集</param>
        /// <param name="pbocCounts">成功获取到的金融数据量</param>
        /// <returns>金融数据</returns>
        public override List<ICData> GetPbocAllDatas(List<string> pbocFilePaths, out int pbocCounts)
        {
            List<ICData> allPbocIcDatas = new List<ICData>();
            List<ICData> finalDatas = new List<ICData>();
            ICData pbocIcData = new ICData();

            FileStream fs = null;
            int allDataCounts = 0;//总条数
      
            foreach (string pbocFile in pbocFilePaths)
            {
                #region 获取每个文件的数据
                fs = File.OpenRead(pbocFile);
                //获取单个文件记录条数            
                int count = pbocBase.GetRecordCounts(fs, config);
                //记录数为0直接返回
                if (count == 0)
                {
                    pbocCounts = 0;
                    return null;
                }
                //定位指针位置
                pbocBase.setPosition(fs, config);
                if (count != -1)
                {
                    #region 文件头有给记录数情况
                    //获取所有数据
                    for (int i = 0; i < count; i++)
                    {
                        pbocIcData = pbocBase.GetDgiDataGeneralMode(fs, config);//获取数据
                        pbocIcData.Extend3 = Path.GetFileName(pbocFile);
                        //pbocIcData.PbocDataID = reacordId++.ToString();
                        if (!string.IsNullOrEmpty(config.icDataCheckRegex))
                            CheckData(pbocIcData, config.icDataCheckRegex,config.trackDataCheckRegex,config.bankCardIdCheckRegex,config.personIdCheckRegex);//检查数据
                        allPbocIcDatas.Add(pbocIcData);
                    }
                    #endregion
                }
                else //无给出记录数处理方式
                {
                    #region 文件无给记录数情况
                    count = 0;
                    while (fs.Position != fs.Length)
                    {
                        pbocIcData = pbocBase.GetDgiDataGeneralMode(fs, config);//获取数据
                        pbocIcData.Extend3 = Path.GetFileName(pbocFile);
  
                        if (!string.IsNullOrEmpty(config.icDataCheckRegex))
                            CheckData(pbocIcData, config.icDataCheckRegex,config.trackDataCheckRegex,
                                config.bankCardIdCheckRegex,config.personIdCheckRegex);//检查数据
                        allPbocIcDatas.Add(pbocIcData);
                        count++;
                    }
                    #endregion
                }
                //统计总的条数
                allDataCounts += count;
                fs.Close();
                #endregion
            }

            //过滤数据
            if (!string.IsNullOrEmpty(config.filterItem))
            {
                finalDatas = commonUtil.FilterDatasWithFile(allPbocIcDatas, context.succeedLogFilePth, config.filterItem);
            }
            else
                finalDatas = allPbocIcDatas;

            pbocCounts = finalDatas.Count;
            pbocDataCounts = finalDatas.Count;
            return finalDatas;
        }
        /// <summary>
        /// 获取金融数据条数
        /// </summary>
        /// <param name="pbocFilePaths">金融数据量</param>
        /// <returns>-1:无法直接读取数据量，其他：数据条数</returns>
        public override int GetPbocAllCounts(List<string> pbocFilePaths)
        {
            try
            {
                FileStream fs = null;
                int allDataCounts = 0;//总条数    
                foreach (string pbocFile in pbocFilePaths)
                {
                    fs = File.OpenRead(pbocFile);
                    //获取单个文件记录条数
                    int count = pbocBase.GetRecordCounts(fs, config);

                    if (count == -1)
                    {
                        if (pbocDataCounts == 0)
                            return -1;
                        else
                            return pbocDataCounts;
                    }
                    //统计总的条数
                    allDataCounts += count;
                    fs.Close();
                }              

                return allDataCounts;
            }
            catch (Exception e)
            {   
                throw new Exception(e.Message);
            }
            
        }
        /// <summary>
        /// 检查数据的正确性
        /// </summary>
        /// <param name="pbocIcData">每条IC数据</param>
        /// <param name="IcDataRegexs">校验每条IC数据的正则</param>
        /// <param name="TrackDataRegex">校验磁条数据的正则</param>
        /// <param name="BankCardIdRegexs">校验银行卡号的正则</param>
        /// <param name="PersonIdRegexs">校验身份证号的正则</param>
        /// <returns>true成功，false失败</returns>
        public override bool CheckData(ICData pbocIcData, string IcDataRegexs,string TrackDataRegex, string BankCardIdRegexs,string PersonIdRegexs)
        {
            string errorMessage = null;
            bool isSucceed = true;
            //检查ICData 
            #region ic数据
            if (!string.IsNullOrEmpty(IcDataRegexs))
            {
                if (!string.IsNullOrEmpty(pbocIcData.PBOCData))
                {
                    if (!Regex.IsMatch(pbocIcData.PBOCData.Trim(), IcDataRegexs.Trim()))
                    {
                        isSucceed = false;
                        errorMessage = "提取的IC数据格式不正确";
                    }
                }
                else
                {
                    isSucceed = false;
                    errorMessage = "提取的IC数据格式不正确";
                }
            }
            #endregion

            //检查磁条数据
            #region 磁条
            if (!string.IsNullOrEmpty(TrackDataRegex))
            {
                if (!string.IsNullOrEmpty(pbocIcData.Track1))
                {
                    if(!Regex.IsMatch(pbocIcData.Track1.Trim(), TrackDataRegex.Trim()))
                    {
                        isSucceed = false;
                        errorMessage = "提取的磁条格式不正确";
                    }          
                }
            }
            #endregion

            //检查银行卡号
            #region 银行卡号
            if (!string.IsNullOrEmpty(BankCardIdRegexs))
            {
                if (!string.IsNullOrEmpty(pbocIcData.BankCardID))
                {
                    if (!Regex.IsMatch(pbocIcData.BankCardID.Trim(), BankCardIdRegexs.Trim()))
                    {
                        isSucceed = false;
                        errorMessage = "提取的银行卡号格式不正确";
                    }
                }
            }
            #endregion

            //检查身份证号
            #region 身份证号
            if (!string.IsNullOrEmpty(PersonIdRegexs))
            {
                if (!string.IsNullOrEmpty(pbocIcData.PersonID))
                {
                    if (!Regex.IsMatch(pbocIcData.PersonID.Trim(), PersonIdRegexs.Trim()))
                    {
                        isSucceed = false;
                        errorMessage = "提取的身份证号格式不正确";
                    }
                }
            }
            #endregion

            if (!isSucceed)
                throw new Exception(errorMessage);

            return isSucceed;
        }      
    }
    /// <summary>
    /// 《建行模式金融数据解析核心类》
    /// 该模式仅支持建行数据的解析
    /// </summary>
    public class PbocFileCoreJHClass : PbocFileCore
    {
        #region 建行解析动态库
        [DllImport("AHMAS_IC_DLL.dll")]
        public static extern int ICDataProcess(string filePath, StringBuilder bankCard, StringBuilder personalID, StringBuilder ICdata);
        #endregion

        static PbocFileConfigJH config = null;
        static Context context;
        public PbocFileCoreJHClass getInstance()
        {
            if (isGetConfigSucceed())
            {
                context = Context.GetConfig();
                return new PbocFileCoreJHClass();
            }
            return null;
        }
        private bool isGetConfigSucceed()
        {
            config = PbocFileConfigJH.GetConfig();
            if (config == null)
                return false;
            else
                return true;
        }
        public override List<ICData> GetPbocAllDatas(List<string> pbocFilePaths, out int pbocCounts)
        {
            List<ICData>  pbocDatas = new List<ICData>();
            StringBuilder bankCardId= new StringBuilder(50);
            StringBuilder personId = new StringBuilder(50);
            StringBuilder _icData = new StringBuilder(6000);
            ICData icData = null;

            foreach (string file in pbocFilePaths)
            {
                int ret = ICDataProcess(file, bankCardId, personId, _icData);
                if (ret != 0 || bankCardId.Length == 0 || personId.Length == 0 || _icData.Length == 0)
                    throw new Exception(string.Format("提取文件：{0}的金融数据失败",file));

                icData = new ICData();
                icData.BankCardID = bankCardId.ToString();
                //icData.PersonID = personId.ToString();
                icData.PBOCData = _icData.ToString();
                icData.Extend3 = Path.GetFileName(file);
                //检查格式
                CheckData(icData, config.icDataCheckRegex,null,config.bankCardIdCheckRegex,null);
                pbocDatas.Add(icData);
            }
            pbocCounts = pbocDatas.Count;
            return pbocDatas;
        }
        public override bool CheckData(ICData pbocIcData, string IcDataRegexs, string TrackDataRegex, string BankCardIdRegexs, string PersonIdRegexs)
        {
            string errorMessage = null;
            bool isSucceed = true;
            /////////////检查ICData //////////////
            #region ic数据
            if (!string.IsNullOrEmpty(IcDataRegexs))
            {
                if (!string.IsNullOrEmpty(pbocIcData.PBOCData))
                {
                    if (!Regex.IsMatch(pbocIcData.PBOCData.Trim(), IcDataRegexs.Trim()))
                    {
                        isSucceed = false;
                        errorMessage = "提取的IC数据格式不正确";
                    }
                }
                else
                {
                    isSucceed = false;
                    errorMessage = "提取的IC数据格式不正确";
                }
            }
            #endregion

            ///////////////检查磁条数据////////////
            //#region 磁条
            //if (!string.IsNullOrEmpty(TrackDataRegex))
            //{
            //    if (!string.IsNullOrEmpty(pbocIcData.Track1))
            //    {
            //        if (!Regex.IsMatch(pbocIcData.Track1.Trim(), TrackDataRegex.Trim()))
            //        {
            //            isSucceed = false;
            //            errorMessage = "提取的磁条格式不正确";
            //        }
            //    }
            //}
            //#endregion

            /////////////检查银行卡号///////////
            #region 银行卡号
            if (!string.IsNullOrEmpty(BankCardIdRegexs))
            {
                if (!string.IsNullOrEmpty(pbocIcData.BankCardID))
                {
                    if (!Regex.IsMatch(pbocIcData.BankCardID.Trim(), BankCardIdRegexs.Trim()))
                    {
                        isSucceed = false;
                        errorMessage = "提取的银行卡号格式不正确";
                    }
                }
            }
            #endregion

            ///////////////检查身份证号///////////
            //#region 身份证号
            //if (!string.IsNullOrEmpty(PersonIdRegexs))
            //{
            //    if (!string.IsNullOrEmpty(pbocIcData.PersonID))
            //    {
            //        if (!Regex.IsMatch(pbocIcData.PersonID.Trim(), PersonIdRegexs.Trim()))
            //        {
            //            isSucceed = false;
            //            errorMessage = "提取的身份证号格式不正确";
            //        }
            //    }
            //}
            //#endregion

            if (!isSucceed)
                throw new Exception(errorMessage);

            return isSucceed;
        }
        public override int GetPbocAllCounts(List<string> pbocFilePaths)
        {
            return pbocFilePaths.Count; 
        }
    }
   
}